home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10625 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  57 lines

  1. Newsgroups: comp.lang.c++
  2. Path: nntp.coast.net!torn!news!apollo!saed
  3. From: saed@engn.uwindsor.ca (Saed Aryan)
  4. Subject: Re: friend functions and access to private variables...
  5. X-Nntp-Posting-Host: apollo.engn.uwindsor.ca
  6. Message-ID: <Dnyy92.MLL@news.uwindsor.ca>
  7. Keywords: friend
  8. Sender: news@news.uwindsor.ca (Usenet)
  9. Reply-To: saed@engn.uwindsor.ca
  10. Organization: VLSI Research Group - University of Windsor
  11. Date: Fri, 8 Mar 1996 21:55:50 GMT
  12.  
  13. Hi all,
  14.  
  15. Dariusz Piatkowski asked:
  16. >I'm dealing with two classes, where a member function of class A is declared as
  17. >a friend function of class B.
  18. >Unfortunately this does not allow the friend function access to private variables in
  19. >class B...what gives? Is it not legal to make such a declaration?
  20.  
  21. well, I guess you're right! 
  22.  
  23. --- A friend method of a non friend class has no access to the private member data.
  24.     Apparently the class to which that method belongs must be a friend. The friend
  25.     declaration of that method is then redundant. 
  26.  
  27. The code snippet below (compilable) will show what works and what doesn't.
  28.  
  29. Aryan.
  30.  
  31. //---- begin code
  32. class X {
  33.     friend void yMethod(X x);
  34.     friend void aFunction(X x);
  35.     friend class Z;
  36.     private: int a;
  37.     };
  38.  
  39. void aFunction(X x){x.a=1;};
  40. // okay: aFunction is friend of class X and may access private member 'a' of X
  41.  
  42. class Z { public: void zMethod(X x){x.a=1;}; };
  43. // okay: class Z is friend of X, zMethod may access private member 'a' of X
  44.  
  45. class Y { public: void yMethod(X x){x.a=1;}; };
  46. // error: member `a' is a private member of class `X' (class Y is not a friend)
  47. // this is Dariusz's question
  48.  
  49. void aFunction(X x, int i){ return x.a=1; };
  50. // error: member `a' is a private member of class `X'
  51. // (different signature, not a friend)
  52.  
  53. main(){}
  54. //---end of code  
  55.  
  56.  
  57.